package fr.greta.centre.action;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fr.greta.centre.dao.CandidatDAO;
import fr.greta.centre.dao.CandidatDAOImpl;
import fr.greta.centre.metier.Candidat;


public class Reconnaitre extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true); 
		  session.invalidate();
		  request.getRequestDispatcher("index.jsp").forward(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String email=request.getParameter("email");
		String password=request.getParameter("password");
		String idpromotion =request.getParameter("idPromotion");
		int idPromotion = Integer.parseInt(idpromotion); 
		if(email == null || email.equals("") || password.equals("") || password == null){
			request.setAttribute("message", "E-mail et/ou mot de passe requis");
			request.setAttribute("action", "Reconnaitre");
			request.setAttribute("idPromotion", idPromotion);
			request.getRequestDispatcher("formCandidater.jsp").forward(request, response);
		}else{
			Candidat unCandidat=null;
			CandidatDAOImpl dao=new CandidatDAOImpl();
			try {
				 unCandidat=dao.findByEmailAndPassword(email, password);
				 if(unCandidat == null){
					 request.setAttribute("message", "Utilisateur inconnu");
					 request.setAttribute("action", "Candidater");
					 request.getRequestDispatcher("formCandidater.jsp").forward(request, response);
				 }else{
					// Recupere la session
					  HttpSession session = request.getSession(true); 
					  session.setAttribute("candidat", unCandidat);
					  session.setAttribute("idPromotion", idPromotion);
					 //request.setAttribute("candidat", unCandidat);
					// request.setAttribute("idPromotion", idPromotion);
					  //request.getRequestDispatcher("candidater.jsp").forward(request, response);
					 request.getRequestDispatcher("formCandidater.jsp").forward(request, response);
				 }
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
